package com.lxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxy.common.utils.Assert;
import com.lxy.entity.*;
import com.lxy.mapper.*;
import com.lxy.service.SkuService;
import com.lxy.service.SpuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    SkuMapper skuMapper;

    @Autowired
    SpuDetailMapper spuDetailMapper;

    @Autowired
    SkuStockMapper skuStockMapper;

    @Autowired
    SpuExtensionMapper spuExtensionMapper;

    @Autowired
    AttrMapper attrMapper;

    @Autowired
    AttrValueMapper attrValueMapper;

    @Autowired
    SpuAttrValueMapper spuAttrValueMapper;

    @Autowired
    SpuSkuAttrValueMapper spuSkuAttrValueMapper;

    /**
     * 保存spu
     *
     * @param spu
     * @return
     */
    @Transactional
    @Override
    public boolean save(Spu spu) {

        //获取用户上下文信息 --店铺id、店铺分类id
        int shopId = 001;


        //保存sku
        int rs = spuMapper.insert(spu);
        spu.setShopId(shopId);
        Assert.isZero(rs, "保存spu失败");

        //保存spu详情
        SpuDetail spuDetail = new SpuDetail()
                .setSpuId(spu.getSpuId())
                .setDetail(spu.getDetail());
        rs = spuDetailMapper.insert(spuDetail);
        Assert.isZero(rs, "保存spu详情失败");

        //原子类包装值
        AtomicInteger totalStock = new AtomicInteger(0);

        //保存sku
        if (null != spu.getSkuList() && spu.getSkuList().size() > 0) {
            spu.getSkuList().forEach(el -> {
                el.setSpuId(spu.getSpuId());
                int tmp = skuMapper.insert(el);
                Assert.isZero(tmp, "保存sku失败");
                totalStock.addAndGet(el.getStock());

                //获取自动生成的skuID
                int skuId = el.getSkuId();

                //保存skuStock
                SkuStock skuStock = new SkuStock()
                        .setSkuId(skuId)
                        .setStock(el.getStock())
                        .setActualStock(el.getStock());
                tmp = skuStockMapper.insert(skuStock);
                Assert.isZero(tmp, "保存sku库存失败");
            });
        }

        int finalStock = totalStock.get();

        //保存spu库存
        SpuExtension spuExtension = new SpuExtension();
        spuExtension.setSpuId(spu.getSpuId());
        spuExtension.setStock(finalStock);
        spuExtension.setActualStock(finalStock);
        rs = spuExtensionMapper.insert(spuExtension);
        Assert.isZero(rs, "保存spu库存失败");

        //保存attr（规格）
        if (null != spu.getAttrList() && spu.getAttrList().size() > 0) {
            for (Attr attr : spu.getAttrList()) {
                attr.setShopId(shopId);
                rs = attrMapper.insert(attr);
                Assert.isZero(rs, "保存attr（规格）失败");
                //保存attrValue
                if (null != attr.getAttrValueList() && attr.getAttrValueList().size() > 0) {
                    for (AttrValue attrValue : attr.getAttrValueList()) {

                        attrValue.setAttrId(attr.getAttrId());
                        rs = attrValueMapper.insert(attrValue);
                        Assert.isZero(rs, "保存attr（规格值）失败");
                        //保存spu_attr_value
                        SpuAttrValue spuAttrValue = new SpuAttrValue()
                                .setSpuId(spu.getSpuId())
                                .setAttrId(attr.getAttrId())
                                .setAttrName(attr.getName())
                                .setAttrValueId(attrValue.getAttrValueId())
                                .setAttrValueName(attrValue.getValue());
                        rs = spuAttrValueMapper.insert(spuAttrValue);
                        Assert.isZero(rs, "保存spu_attr_value失败");

                        //保存spu_sku_attr_value
                        if (attr.getAttrType() == 0) {
                            for (Sku sku : spu.getSkuList()) {
                                String[] attrValuesIds = sku.getAttrs().split(",");
                                for (String s : attrValuesIds) {
                                    if (s.equals(attrValue.getAttrValueId().toString())) {
                                        SpuSkuAttrValue spuSkuAttrValue = new SpuSkuAttrValue();
                                        spuSkuAttrValue.setSpuId(spu.getSpuId());
                                        spuSkuAttrValue.setSkuId(sku.getSkuId());
                                        spuSkuAttrValue.setAttrId(attr.getAttrId());
                                        spuSkuAttrValue.setAttrName(attr.getName());
                                        spuSkuAttrValue.setAttrValueId(attrValue.getAttrValueId());
                                        spuSkuAttrValue.setAttrValueName(attrValue.getValue());
                                        rs = spuSkuAttrValueMapper.insert(spuSkuAttrValue);
                                        Assert.isZero(rs, "保存spu_sku_attr_value失败");
                                    }
                                }

                            }


                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 根据spuId查询商品
     *
     * @param spuId
     * @return
     */
    public Spu queryBySpuId(Long spuId) {

        Spu spu = spuMapper.selectById(spuId);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spu.getSpuId());
        List<Sku> skuList = skuMapper.selectList(queryWrapper);
        //查询sku库存
        skuList.forEach(sku ->{
            QueryWrapper<SkuStock> skuStockWrapper = new QueryWrapper<>();
            skuStockWrapper.eq("sku_id",sku.getSkuId())
                    .select("stock");
            sku.setStock(skuStockMapper.selectOne(skuStockWrapper).getStock());
        });
        spu.setSkuList(skuList);
        QueryWrapper attrWrapper = new QueryWrapper<>();
        attrWrapper.eq("shop_id", spuId);
        //查询attr_value
        List<Attr> attrs = attrMapper.selectList(attrWrapper);
        attrs.forEach(attr -> {
            QueryWrapper attrValueWrapper = new QueryWrapper<>();
            attrValueWrapper.eq("attr_id",attr.getAttrId());
            attr.setAttrValueList(attrValueMapper.selectList(attrValueWrapper));
        });
        spu.setAttrList(attrs);
        return spu;
    }
}
